package com.xunmall.engine.util;

import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * @author wangyanjing
 * @date 2018/9/11
 */
public class WebSocketUtil {

    /**
     * 简单实用map进行存储在线的session
     */
    private static final Map<String, Session> ONLINE_SESSION = new ConcurrentHashMap<>();

    public static void addSession(String userNick, Session session) {
        ONLINE_SESSION.put(userNick, session);
    }

    public static void removeSession(String userNick) {
        ONLINE_SESSION.remove(userNick);
    }

    public static void sendMessage(Session session, String message) {
        if (session == null) {
            return;
        }
        // getAsyncRemote()和getBasicRemote()异步与同步
        RemoteEndpoint.Async async = session.getAsyncRemote();
        async.sendText(message);
    }

    public static void sendMessageForAll(String message) {
        ONLINE_SESSION.forEach((sessionId, session) -> {
            sendMessage(session, message);
        });
    }


}
